package config

import (
	"fmt"
	"os"

	"github.com/google/uuid"
	"gopkg.in/ini.v1"
)

type Config struct {
	ConfServer  ConfServer
	ConfClient  ConfClient
	ConfYserver ConfYserver
}

type ConfServer struct {
	Uuid    string
	Enabled bool
	Port    int
}

type ConfClient struct {
	Uuid    string
	Enabled bool
	Port    int
}

type ConfYserver struct {
	Uuid     string
	Enabled  bool
	Port     int
	User     string
	Password string
	Savepath string
}

var filePath string

func Init(fp string) {
	filePath = fp + "/config.ini"
}

func LoadConfigFromFile() (*Config, error) {
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		// File does not exist, create a new config with default values
		defaultConf := &Config{
			ConfServer: ConfServer{
				Uuid:    uuid.New().String(),
				Enabled: true,
				Port:    8080,
			},
			ConfClient: ConfClient{
				Uuid:    uuid.New().String(),
				Enabled: true,
				Port:    8081,
			},
			ConfYserver: ConfYserver{
				Uuid:     uuid.New().String(),
				Enabled:  false,
				Port:     8082,
				User:     "admin",
				Password: "admin",
				Savepath: "",
			},
			//... other default values ...
		}

		// Write default config to file
		err := SaveConfigToFile(defaultConf)
		if err != nil {
			return nil, fmt.Errorf("Error writing default config to file: %v", err)
		}

		// Return default config
		return defaultConf, nil
	} else if err != nil {
		// Other error when trying to stat the file
		return nil, err
	}

	// Config file exists, load it
	conf := &Config{}
	err := ini.MapTo(conf, filePath)
	if err != nil {
		return nil, fmt.Errorf("Error parsing config file: %v", err)
	}

	return conf, nil
}

func SaveConfigToFile(config *Config) error {
	cfg := ini.Empty()
	err := ini.ReflectFrom(cfg, config)
	if err != nil {
		return err
	}

	return cfg.SaveTo(filePath)
}
